<?php namespace App\Controllers;

use App\Models\StudyLocationModel;
use App\Models\KeywordMappingModel;

class Search extends BaseController
{
    public function index()
    {
        $keyword = $this->request->getGet('keyword');
        $studyLocationModel = new StudyLocationModel();
        $keywordMappingModel = new KeywordMappingModel();

        if ($keyword) {
            // 在 keyword_mapping 表中搜索关键词
            $matchingMappings = $keywordMappingModel->where('keyword', $keyword)->findAll();

            // 提取 study_location_id
            $studyLocationIds = [];
            foreach ($matchingMappings as $mapping) {
                $studyLocationIds[] = $mapping['page_id'];
            }

            // 根据提取的 study_location_id 获取对应的 study_location 记录
            if (!empty($studyLocationIds)) {
                // $searchResults = $studyLocationModel->whereIn('id', $studyLocationIds)->findAll();
                $searchResults = $studyLocationModel
                    ->select('study_location.*, SUM(page_links.score) as total_score')
                    ->join('page_links', 'study_location.id = page_links.to_page_id', 'left')
                    ->whereIn('study_location.id', $studyLocationIds)
                    ->where('study_location.is_open', 1)
                    ->groupBy('study_location.id')
                    ->orderBy('total_score', 'DESC')  // 按总分降序排列
                    ->orderBy('study_location.location_order', 'ASC')  // 按总分降序排列
                    ->findAll();
            } else {
                $searchResults = [];
            }
        } else {
            $searchResults = [];
        }

        $totalRecords = count($searchResults);
        $recordsPerPage = 3;
        $totalPages = ceil($totalRecords / $recordsPerPage);
        $currentPage = isset($_GET['page']) ? intval($_GET['page']) : 1;
        $startIndex = ($currentPage - 1) * $recordsPerPage;
        $endIndex = min($startIndex + $recordsPerPage, $totalRecords);
        $searchResults = array_slice($searchResults, $startIndex, $recordsPerPage);

        $data = [
            'keyword' => $keyword,
            'searchResults' => $searchResults,
            'totalRecords' => $totalRecords,
            'recordsPerPage' => $recordsPerPage,
            'totalPages' => $totalPages,
            'currentPage' => $currentPage,
            'startIndex' => $startIndex,
            'endIndex' => $endIndex
        ];

        return view('search', $data);
    }
}